package com.qf.dao.Impl;


import com.qf.dao.ProductDao;
import com.qf.pojo.Product;
import com.qf.utils.DruidUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class ProductDaoImpl implements ProductDao {




    //创建JdbcTemplate对象，依赖数据源Datasource
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtil.getDataSource());

    @Override
    public List<Product> findAll() {
        String sql="select * from  product ";
        List<Product> query = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Product.class));
        return query;
    }


    @Override
    public Product findById( int id) {
        String sql="select * from product where pid=?";
        List<Product> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class), id);
        //返回值是否为空判断
        if (query!=null&&query.size()==1){
            return  query.get(0);
        }
        return null;

    }

    //根据id修改产品信息
    @Override
    public int  UpdateProduct(Product product) {
        String sql="update product set pname=?,price=?,flag=?,cid=? where pid=?";
        int update = jdbcTemplate.update(
                sql, product.getPname(), product.getPrice(), product.getFlag(), product.getCid(), product.getPid());
           return update;
    }


    //删除一条商品
    @Override
    public int deleteProductById(int id) {
        String sql="delete from product where pid=?";
        int update = jdbcTemplate.update(sql, id);
        return update;
    }


    //添加商品


    @Override
    public int createProduct(Product product) {
        String sql="insert into  product values(null,?,?,?,?)";
        int update = jdbcTemplate.update(sql, product.getPname(), product.getCid(), product.getFlag(), product.getCid());
        return update ;
    }
}
